<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="退单号" prop="tradeNo">
        <el-input
          v-model="queryParams.tradeNo"
          placeholder="请输入退款订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select
          v-model="queryParams.orderType"
          placeholder="请选择订单类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_oder_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款方式" prop="refundWay">
        <el-select
          v-model="queryParams.refundWay"
          placeholder="请选择退款方式"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_refund_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 将日期格式设置为毫秒时间戳 -->
      <el-form-item label="开始时间" prop="timeFrom">
        <el-date-picker
          v-model="queryParams.timeFrom"
          type="date"
          value-format="timestamp"
          placeholder="请选择开始时间"
          clearable
        />
      </el-form-item>
      <!-- 将日期格式设置为毫秒时间戳 -->
      <el-form-item label="结束时间" prop="timeTo">
        <el-date-picker
          v-model="queryParams.timeTo"
          type="date"
          value-format="timestamp"
          placeholder="请选择结束时间"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          style="height: 40px; width: 120px; font-size: 14px; margin-left: 20px"
          type="primary"
          plain
          @click="popup"
          >退款处理</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refundOderList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退款订单号" align="center" prop="tradeNo" />
      <el-table-column
        label="退款时间"
        align="center"
        prop="refundTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.refundTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center" prop="orderType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_oder_type"
            :value="scope.row.orderType"
          />
        </template>
      </el-table-column>

      <el-table-column label="退款金额" align="center">
        <template slot-scope="scope">
          {{
            (scope.row.refundFee / 100).toLocaleString(undefined, {
              minimumFractionDigits: 0,
              maximumFractionDigits: 2,
            })
          }}
        </template>
      </el-table-column>
      <el-table-column label="退款方式" align="center" prop="refundWay">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_refund_type"
            :value="scope.row.refundWay"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改PC后管对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="650px"
      append-to-body
      v-loading="loading"
      @close="cancel"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="退款处理" prop="tradeNo">
          <div style="display: flex; align-items: center">
            <el-input
              v-model="form.tradeNo"
              placeholder="请输入退单号"
              clearable
              style="flex: 1; margin-right: 12px"
            />
            <el-button
              style="
                height: 36px;
                width: 100px;
                font-size: 12px;
                border-radius: 5px;
              "
              icon="el-icon-search"
              size="mini"
              @click="handleEnter"
            >
              查询订单
            </el-button>
          </div>
          <span style="color: red" v-show="OderMag">{{ OderMag }}</span>
        </el-form-item>
      </el-form>
      <div></div>
      <el-table
        v-show="Oderloading && Object.keys(refundOderInfo).length > 0"
        :data="[refundOderInfo]"
      >
        <el-table-column label="退款金额" align="center">
          <template slot-scope="scope">
            {{
              (scope.row.amount / 100).toLocaleString(undefined, {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2,
              })
            }}
          </template>
        </el-table-column>
        <el-table-column label="订单类型" align="center" prop="orderType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_oder_type"
              :value="scope.row.orderType"
            />
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template v-slot="scope">
            <span v-if="scope.row.orderStatus == 1">支付成功</span>
            <span v-else-if="scope.row.orderStatus == 2">退款成功</span>
            <span v-else>未知状态</span>
          </template>
        </el-table-column>

        <el-table-column label="订单时间" prop="orderTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 如果 refundOderInfo 为空，显示一个提示 -->
      <el-empty
        v-if="Object.keys(refundOderInfo).length <= 0"
        description="没有退款订单信息"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          v-show="Oderloading"
          @click="refundOder"
          :disabled="isProcessing"
          >确认退款</el-button
        >

        <el-button @click="cancel" v-show="!Oderloading">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRefundOder,
  getRefundOder,
  tradeRefund,
} from "@/api/pcAdmin/refundOder";

export default {
  name: "RefundOder",
  dicts: ["sys_oder_type", "sys_refund_type"],
  data() {
    return {
      // 标记是否正在处理退款
      isProcessing: false,
      //查询出来的订单提示语
      OderMag: "",
      // PC订单详情
      refundOderInfo: {},
      Oderloading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // PC后管表格数据
      refundOderList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        tradeNo: null,
        orderType: null,
        refundWay: null,
        refundTime: null,
        timeFrom: null, // 开始时间
        timeTo: null, // 结束时间
        refundFee: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**查询交易号 */
    handleEnter() {
      // 判断 tradeNo 是否为空
      if (!this.form.tradeNo || this.form.tradeNo.trim() === "") {
        // 如果为空，给出提示
        this.OderMag = "请填写退单号！";
        return;
      }

      getRefundOder(this.form.tradeNo).then((response) => {
        if (response.code == 200 && response.data.code == 0) {
          this.refundOderInfo = response.data.data;
          if (Object.keys(this.refundOderInfo).length != 0 ) {
            this.Oderloading = true;
            this.OderMag = null;
            if (this.refundOderInfo.orderStatus == 2) {
              this.isProcessing = true;
            } else {
              this.isProcessing = false;
            }
          } else {
            this.refundOderInfo = {};
            this.Oderloading = false;
            // this.OderMag = "不能退款";
          }
        }
      });
    },
    /**
     * 主动退款
     */

    refundOder() {
      // 防止重复点击
      if (this.isProcessing) return;
      this.isProcessing = true; // 开始处理退款
      // 先判断 refundOderInfo 是否为空
      if (!this.refundOderInfo) {
        this.$modal.msgError("无退款订单信息，无法退款");
        return;
      }

      this.loading = true;
      this.Oderloading = true;
      setTimeout(() => {
        tradeRefund(this.refundOderInfo.orderNo).then((response) => {
          if (response.code == 200 && response.data.code == 0) {
            this.$modal.msgSuccess("退款成功");
            this.handleEnter();
            // 退款操作完成，恢复状态
            this.isProcessing = false;
            this.loading = false;
          } else {
            // 出现错误时也要恢复按钮状态
            this.isProcessing = false;
            this.loading = false;
            this.$modal.msgError("退款失败");
          }
        });
      }, 1000);
    },

    /** 查询PC后管列表 */
    getList() {
      this.loading = true;
      listRefundOder(this.queryParams).then((response) => {
        this.refundOderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.Oderloading = false;
      this.form.tradeNo = null;
      this.OderMag = null;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tradeNo: null,
        orderType: null,
        refundWay: null,
        refundTime: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.tradeNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加PC后管";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      this.open = true;
      this.title = "修改PC后管";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.tradeNo != null) {
          } else {
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tradeNos = row.tradeNo || this.ids;
      this.$modal
        .confirm('是否确认删除PC后管编号为"' + tradeNos + '"的数据项？')
        .then(function () {
          return delRefundOder(tradeNos);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 弹窗按钮 */
    popup() {
      this.title = "退款处理";
      this.open = true;
    },
    parseTime(time, format) {
      // 时间戳格式化函数
      const date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
      };
      return format.replace(/{(y|m|d)+}/g, (result, key) => {
        return formatObj[key];
      });
    },
  },
};
</script>
